package com.kit.data.kitopeso.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.IntentSenderRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.JsonObject;
import com.kit.data.kitopeso.KitoApp;
import com.kit.data.kitopeso.PathMaping;
import com.kit.data.kitopeso.R;
import com.kit.data.kitopeso.base.BaseActivity;
import com.kit.data.kitopeso.base.BaseParams;
import com.kit.data.kitopeso.databinding.KitoSettingActivityBinding;
import com.kit.data.kitopeso.net.PU;
import com.kit.data.kitopeso.net.RxHttp;
import com.kit.data.kitopeso.net.U;
import com.kit.data.kitopeso.tools.AESCryptUtilJar;
import com.kit.data.kitopeso.tools.DateUtils;
import com.kit.data.kitopeso.tools.JsonParse;
import com.kit.data.kitopeso.tools.LogUtil;
import com.kit.data.kitopeso.tools.OrderUtils;
import com.kit.data.kitopeso.tools.PopUtils;
import com.kit.data.kitopeso.tools.ResUtils;
import com.kit.data.kitopeso.tools.SpUtils;
import com.kit.data.kitopeso.tools.ViewUtils;
import com.xin.data.turning.device.ImmediateUpdateManager;

import java.util.HashMap;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;

public class KitoSettingActivity extends BaseActivity<KitoSettingActivityBinding> {

    int time;

    private final int TIME_WHAT = 1;

    TextView tvOk;

    ImmediateUpdateManager updateManager = null;


    @Override
    protected KitoSettingActivityBinding initViewBinding(LayoutInflater inflater) {
        return KitoSettingActivityBinding.inflate(inflater);
    }

    @Override
    protected void initView() {


        binding.tvBk.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            finish();
        });
        binding.tvBtn.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P163, "");
            showLogOUt();
        });
        binding.tvDelete.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P162, "");
            int state = OrderUtils.getOrderStatus();
            LogUtil.e("me", "state->" + state);
            if (state <= 0 || state > 5) {
                time = 10;
                showDeleteUser();
                mHandler.sendEmptyMessageDelayed(TIME_WHAT, 1000);
            } else {
                Toast.makeText(getActivity(), ResUtils.s(R.string.delete_hit), Toast.LENGTH_LONG).show();
            }
        });


        binding.tvCheckLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewUtils.viewScale(v);
                PU.userBuriedPoint(PU.P1631, "");
                if (updateManager != null) {
                    updateManager.checkAndStartUpdateAsync(new Function0<Unit>() {
                        @Override
                        public Unit invoke() {
                            Toast.makeText(getActivity(), ResUtils.s(R.string.update_hit3), Toast.LENGTH_LONG).show();
                            return null;
                        }
                    }, null);
                } else {
                    Toast.makeText(getActivity(), ResUtils.s(R.string.update_hit3), Toast.LENGTH_LONG).show();
                }
            }
        });


        if (OrderUtils.isUpdate(getActivity()) || OrderUtils.isForceUpdate(getActivity())) {
            initUpdate();
            binding.tvDot.setVisibility(View.VISIBLE);
        } else {
            binding.tvDot.setVisibility(View.GONE);
        }

    }

    @Override
    protected void initData() {
        UP_TYPE1 = PU.P159;
        UP_TYPE2 = PU.P160;

        int radius = getResources().getDimensionPixelSize(R.dimen.dp_14);
        Glide.with(this)
                .load(R.mipmap.logo)
                .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(radius, 0, RoundedCornersTransformation.CornerType.ALL)))
                .into(binding.tvIcon);

        String androidVersion = BaseParams.getVersionName(this);
        binding.tvVer.setText(ResUtils.s(R.string.setting_ver, androidVersion));

    }

    @Override
    protected void onResume() {
        super.onResume();
        dropUserData("GET");
    }

    @SuppressLint("HandlerLeak")
    final
    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == TIME_WHAT) {
                mHandler.removeMessages(TIME_WHAT);
                time = time - 1;
                if (time > 0) {
                    showDeleteUser();
                    mHandler.sendEmptyMessageDelayed(TIME_WHAT, 1000);
                } else {
                    showDeleteUser();
                }
            }
        }
    };

    void showDeleteUser() {
        String okStr;
        if (time > 0) {
            okStr = ResUtils.s(R.string.user_delete_btn2) + "(" + time + ")";
        } else {
            okStr = ResUtils.s(R.string.user_delete_btn2);
        }
        if (tvOk == null) {
            tvOk = PopUtils.showDeleteUserPop(getActivity(), binding.tvBtn, (title, value, position, index) -> {
                if (title.equals("0")) {
                    tvOk.setText(ResUtils.s(R.string.user_delete_btn2));
                    tvOk.setSelected(false);
                } else {
                    dropUserData("DROP");
                }
                mHandler.removeMessages(TIME_WHAT);
                tvOk = null;
            });
        }
        tvOk.setText(okStr);
        tvOk.setSelected(time <= 0);
    }

    void showLogOUt() {
        exit();
    }

    void dropUserData(String type) {
        showLoading("");
        String token = SpUtils.get_string(this, SpUtils.KEY_TOKEN, "");
        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[89], U.URL_MAIN_PRODUCT, token);
        json.addProperty("type", type);


        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_MAIN_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }
        String data = AESCryptUtilJar.encryptDefault(json.toString());
        LogUtil.e("me", json + "<-dropUserData post->" + data);
        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        hideLoading();
                        if (!TextUtils.isEmpty(s)) {
                            String json1 = AESCryptUtilJar.decryptDefault(s);
                            LogUtil.e("me", "dropUserData json->" + json1);
                            if (type.equalsIgnoreCase("GET")) {
                                String showDropButton = JsonParse.dropUserDataJson2Obj(json1);
                                if (!TextUtils.isEmpty(showDropButton)) {
                                    if (showDropButton.equalsIgnoreCase("YES")) {
                                        binding.tvDelete.setVisibility(View.VISIBLE);
                                    } else {
                                        binding.tvDelete.setVisibility(View.INVISIBLE);
                                    }
                                }
                            } else {
                                if (JsonParse.getCode(json1)) {
                                    exit();
                                } else {
                                    showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.login_faile));
                    }

                    @Override
                    public void onComplete() {
                        hideLoading();
                    }
                });
    }

    void exit() {
        SpUtils.save_string(getActivity(), SpUtils.KEY_PHONE, "");
        SpUtils.save_string(getActivity(), SpUtils.KEY_USERID, "");
        SpUtils.save_string(getActivity(), SpUtils.KEY_TOKEN, "");
        SpUtils.save_int(getActivity(), SpUtils.KEY_SCORE_NUM, 0);
        Intent intent = new Intent(getActivity(), KitoLoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        KitoApp.getInstance().clearActivity();
        finish();
    }


    final ActivityResultLauncher<IntentSenderRequest> updateLauncher =
            registerForActivityResult(new ActivityResultContracts.StartIntentSenderForResult(),
                    result -> {
                        try {
                            if (result.getResultCode() == RESULT_OK) {
                                SpUtils.save_boolean(KitoApp.getInstance(), SpUtils.KEY_UPDATE + "_" + U.URL_PHONE + "_" + DateUtils.getYear() + "_" + DateUtils.getMonth() + "_" + DateUtils.getDay(), true);
                            }
                        } catch (Exception e) {
                            LogUtil.e("me", "updateLauncher e->" + e);
                        }
                    });

    void initUpdate() {
        try {
            updateManager = new ImmediateUpdateManager(this, true, updateLauncher, null);
        } catch (Exception e) {
        }
    }


}
